//
//  Date+Ex.swift
//  GhostWorld
//
//  Created by Kam on 2018/4/2.
//  Copyright © 2018 LKGood. All rights reserved.
//

import Foundation

extension Date {
  
  enum CustomerDateFormat: String {
    case server = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZ"
    case dateTime = "yyyy-MM-dd HH:mm:ss"
    case fullDateWithChinese = "yyyy年MM月dd日"
    case dateWithChinese = "yyyy年M月d日"
    case dateTimeWithChinese = "yyyy年MM月dd日 HH:mm:ss"
    case dateTimeWithoutSeconds = "yyyy-MM-dd HH:mm"
    case date = "yyyy-MM-dd"
    case shortdate = "yyyyMMdd"
  }
  
  init?(fromString: String, format: CustomerDateFormat = .dateTime) {
    let formatter = DateFormatter()
    formatter.dateFormat = format.rawValue
    guard let date = formatter.date(from: fromString) else {
      return nil
    }
    self.init(timeInterval: 0, since: date)
  }
  
  func toString(format: CustomerDateFormat = .dateTime) -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = format.rawValue
    return formatter.string(from: self)
  }
  
  func differ(from: Date, units: Set<Calendar.Component>?) -> String {
    var results = [String]()
    let calendar = Calendar.current
    let components = calendar.dateComponents (
      (units == nil ? [.day, .hour, .minute] : units!),
      from: self, to: from
    )
    if let years = components.year {
      results.append("\(years)年")
    }
    if let months = components.month {
      results.append("\(months)月")
    }
    if let days = components.day {
      results.append("\(days)日")
    }
    if let hours = components.hour {
      results.append("\(hours)小时")
    }
    if let minuts = components.minute {
      results.append("\(minuts)小时")
    }
    if let seconds = components.second {
      results.append("\(seconds)秒")
    }
    return results.joined(separator: "")
  }
}
